package com.coocaa.x.app.hall.parser;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.RemoteException;

import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.data.JObject;
import com.coocaa.x.framework.utils.LiteURI;
import com.coocaa.x.service.XServiceManager;
import com.coocaa.x.service.litecontent.LiteContentServiceConnecter;
import com.coocaa.x.service.litecontent.data.store.com_coocaa_hall.RP_Content;
import com.tianci.media.api.Log;
import com.tianci.media.api.SkyMediaApi;
import com.tianci.media.base.SkyMediaItem;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by admin on 2015/6/16.
 */
public class ActionParser implements IParseInterface<ActionParser.ParseIntent> {

    public static class ExceptionData extends JObject{
        public String pkg;
        public String content;

        public ExceptionData(){}
    }

    public class ParseIntent{
        public Intent i = null;
        public String pkgName = "";
        public int type = 0;
        public String content = "";

        public ParseIntent(){}
    }

    private Map<String, ParseIntent> intentMap = new HashMap<String, ParseIntent>();
    public static final int INTENT_VIDEO_FLAG = 1;
    public static final int INTENT_WEB_FLAG = 2;
    public static final int INTENT_APP_FLAG = 3;
    public static final int INTENT_LIST_FLAG = 4;
    public static final int INTENT_ZONE_FLAG = 5;

    @Override
    public ParseIntent parse(String json) throws PackageManager.NameNotFoundException {
        ParseIntent pi = new ParseIntent();
        Intent i = new Intent();
        Log.d("json", "parse  json:" + json);
        if (intentMap.containsKey(json))
            return intentMap.get(json);
        ParserData.Action_Node action = ParserData.Action_Node.parseJObject(json, ParserData.Action_Node.class);
        String actionName = action.value_name;
        pi.content = action.content;
        if(actionName == null || actionName.equals(""))
            return pi;
        if (actionName.equals("start_app")) {
            ParserData.Action_Node.Action_Start_App start_app = ParserData.Action_Node.Action_Start_App.parseJObject(action.value, ParserData.Action_Node.Action_Start_App.class);
            String pkg = start_app.pkg;
            boolean isInstalled = isPackageInstalled(CoocaaApplication.getContext(), pkg);
            if (!isInstalled) {
                ExceptionData data = new ExceptionData();
                data.pkg = pkg;
                data.content = action.content;
                throw new PackageManager.NameNotFoundException(data.toJSONString()) {
                    @Override
                    public void printStackTrace() {
                    }
                };
            }
//            String data = start_app.data;
//            Log.d("json","data:" + data);
//            if(data != null && !data.equals("")) {
            ParserData.Action_Node.Action_Start_App.ExtraData mM = ParserData.Action_Node.Action_Start_App.ExtraData.parseJObject(action.value, ParserData.Action_Node.Action_Start_App.ExtraData.class);
            List<ParserData.Action_Node.Action_Start_App.ExtraData.ExtraItem> list = mM.extraData;
            if (list != null && list.size() > 0) {
                Log.d("json", "list size:" + list.size());
                for (ParserData.Action_Node.Action_Start_App.ExtraData.ExtraItem item : list) {
                    Log.d("json", "key:" + item.key + " value:" + item.value);
                    i.putExtra(item.key, item.value);
                }
            }
//            }
            String name = start_app.value_name;
            if (name.equals("by_activity")) {
                ParserData.Action_Node.Action_Start_App.Action_Start_App_ByActivity byActivity = ParserData.Action_Node.Action_Start_App.Action_Start_App_ByActivity.parseJObject(start_app.value, ParserData.Action_Node.Action_Start_App.Action_Start_App_ByActivity.class);
//                String activity = byActivity.activity;
                String activity = checkStartActivity(pkg, byActivity.activity);
                ComponentName cn = new ComponentName(pkg, activity);
                i.setComponent(cn);
            } else if (name.equals("by_action")) {
                ParserData.Action_Node.Action_Start_App.Action_Start_App_ByAction byAction = ParserData.Action_Node.Action_Start_App.Action_Start_App_ByAction.parseJObject(start_app.value, ParserData.Action_Node.Action_Start_App.Action_Start_App_ByAction.class);
                String saction = byAction.action;
                i.setAction(saction);
                i.setPackage(pkg);
            } else if (name.equals("by_uri")) {
                ParserData.Action_Node.Action_Start_App.Action_Start_App_ByURI byUri = ParserData.Action_Node.Action_Start_App.Action_Start_App_ByURI.parseJObject(start_app.value, ParserData.Action_Node.Action_Start_App.Action_Start_App_ByURI.class);
                String uri = byUri.uri;
                i.setData(Uri.parse(uri));
                i.setPackage(pkg);
            }
//            i.putExtra("pkgName", pkg);
//            i.putExtra("type", INTENT_APP_FLAG);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            pi.pkgName = pkg;
            pi.type = INTENT_APP_FLAG;
        } else if (actionName.equals("start_appzone")) {
            ParserData.Action_Node.Action_Start_AppTopic start_apptopic = ParserData.Action_Node.Action_Start_AppTopic.parseJObject(action.value, ParserData.Action_Node.Action_Start_AppTopic.class);
            String name = start_apptopic.value_name;
            if (name.equals("by_id")) {
                ParserData.Action_Node.Action_Start_AppTopic.Action_Start_AppTopic_ByID byId = ParserData.Action_Node.Action_Start_AppTopic.Action_Start_AppTopic_ByID.parseJObject(start_apptopic.value, ParserData.Action_Node.Action_Start_AppTopic.Action_Start_AppTopic_ByID.class);
                String id = byId.id;
                i.setClass(CoocaaApplication.getContext(), com.coocaa.x.app.hall.topic.HallTopicActivity.class);
                i.putExtra("start_apptopic", id);
//                i.putExtra("type", INTENT_ZONE_FLAG);
                pi.type = INTENT_ZONE_FLAG;
                Log.d("json", "actionpaser  start_appzone id:" + id);
            }
        } else if (actionName.equals("start_applist")) {
            ParserData.Action_Node.Action_Start_AppList start_applist = ParserData.Action_Node.Action_Start_AppList.parseJObject(action.value, ParserData.Action_Node.Action_Start_AppList.class);
            String name = start_applist.value_name;
            if (name.equals("by_id")) {
                ParserData.Action_Node.Action_Start_AppList.Action_Start_AppList_ByID byId = ParserData.Action_Node.Action_Start_AppList.Action_Start_AppList_ByID.parseJObject(start_applist.value, ParserData.Action_Node.Action_Start_AppList.Action_Start_AppList_ByID.class);
                String id = byId.id;
                i.setClass(CoocaaApplication.getContext(), com.coocaa.x.app.hall.list.HallListActivity.class);
                i.putExtra("start_applist", id);
//                i.putExtra("type", INTENT_LIST_FLAG);
                pi.type = INTENT_LIST_FLAG;
                Log.d("json", "actionpaser  start_applist id:" + id);
            }
        } else if (actionName.equals("start_web")) {
            ParserData.Action_Node.Action_Start_Web start_web = ParserData.Action_Node.Action_Start_Web.parseJObject(action.value, ParserData.Action_Node.Action_Start_Web.class);
            String name = start_web.value_name;
            if (name.equals("by_url")) {
                ParserData.Action_Node.Action_Start_Web.Action_Start_Web_ByUrl byUrl = ParserData.Action_Node.Action_Start_Web.Action_Start_Web_ByUrl.parseJObject(start_web.value, ParserData.Action_Node.Action_Start_Web.Action_Start_Web_ByUrl.class);
                String url = byUrl.url;
                int androidVersion = android.os.Build.VERSION.SDK_INT;
                Log.d("action", "by_url  url:" + url + " version:" + androidVersion);
                if (androidVersion > 21) {
                    i.setAction("com.skyworth.tv_browser");
                    i.putExtra("showMenu", false);
                    i.putExtra("url", url);
//                    i.putExtra("type", INTENT_WEB_FLAG);
                    pi.type = INTENT_WEB_FLAG;
                } else {
                    i.setClass(CoocaaApplication.getContext(), com.coocaa.x.app.hall.web.HallWebActivity.class);
                    i.setData(Uri.parse(url));
//                    i.putExtra("type", INTENT_WEB_FLAG);
                    pi.type = INTENT_WEB_FLAG;
                }
            }
        } else if (actionName.equals("start_video")) {
            ParserData.Action_Node.Action_Start_Video start_video = ParserData.Action_Node.Action_Start_Video.parseJObject(action.value, ParserData.Action_Node.Action_Start_Video.class);
            String name = start_video.value_name;
            if (name.equals("by_url")) {
                ParserData.Action_Node.Action_Start_Video.Action_Start_Video_ByUrl byUrl = ParserData.Action_Node.Action_Start_Video.Action_Start_Video_ByUrl.parseJObject(start_video.value, ParserData.Action_Node.Action_Start_Video.Action_Start_Video_ByUrl.class);
                String videoName = byUrl.name;
                String url = byUrl.url;
//                i.putExtra("type", INTENT_VIDEO_FLAG);
                pi.type = INTENT_VIDEO_FLAG;
                i.putExtra("name", videoName);
                i.putExtra("url", url);
                Log.d("play", "videoName:" + videoName + " url:" + url);
            }
        } else {
            i = null;
        }
        pi.i = i;
        if (i != null)
            intentMap.put(json, pi);
        return pi;
    }

    private static boolean isPackageInstalled(Context context, String pkg) {
        PackageManager mPackageManager = context.getApplicationContext().getPackageManager();
        PackageInfo intent;
        try {
            intent = mPackageManager.getPackageInfo(pkg, 0);
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
        if (intent == null)
            return false;
        else
            return true;
    }

    private static String checkStartActivity(String pkg, String activity) {
        Log.d("app", "checkStartActivity  pkg:" + pkg + " activity:" + activity);
        PackageManager pm = CoocaaApplication.getContext().getPackageManager();
        Intent intent = new Intent(Intent.ACTION_MAIN, null);
//        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setPackage(pkg);
        List<ResolveInfo> resolveInfo = null;
//        PackageInfo info = null;
//        try {
//            info = pm.getPackageInfo(pkg, 0);
        resolveInfo = pm.queryIntentActivities(intent, 0);
//        } catch (PackageManager.NameNotFoundException e) {
//            e.printStackTrace();
//        }
        if (resolveInfo != null && resolveInfo.size() > 0) {
            for (ResolveInfo aInfo : resolveInfo) {
                Log.d("app", "checkStartActivity activity:" + aInfo.activityInfo.name + " resolveInfo size:" + resolveInfo.size());
                if (aInfo.activityInfo.name.equals(activity))
                    return activity;
            }
            Log.d("app", "checkStartActivity first name:" + resolveInfo.get(0).activityInfo.name);
            return resolveInfo.get(0).activityInfo.name;
        }
//        if(info != null && info.applicationInfo != null) {
//            String cn = info.applicationInfo.className;
//            Log.d("app", "checkStartActivity cn:" + cn);
//            return cn;
//        }
        return activity;
    }

}
